package com.yuan.web.servlet;

import com.yuan.pojo.User;
import com.yuan.utils.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/login")
public class ServletLogin extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String checkCode = request.getParameter("checkCode");
        String remember = request.getParameter("remember");

        Cookie cookie = new Cookie("username", username);
        cookie.setPath(request.getContextPath());
        if(remember!=null){
            cookie.setMaxAge(7*24*60*60);
        }else{
            cookie.setMaxAge(0);
        }
        response.addCookie(cookie);

        HttpSession session = request.getSession();
        String code = (String) session.getAttribute("code");
        if(checkCode.equals(code)){
                QueryRunner queryRunner = new QueryRunner(DruidUtil.getDataSource());
                String sql="select * from user where username=? and password=?";
            try {
                User user = queryRunner.query(sql, new BeanHandler<>(User.class), username, password);
                if(user!=null){
                   session.setAttribute("user",user);
                    response.sendRedirect("success.jsp");
                }else{
                    session.setAttribute("msg","账户或者密码错误1");
                    request.getRequestDispatcher("login.jsp").forward(request,response);
                }

            } catch (Exception e) {
                e.printStackTrace();
                session.setAttribute("msg","账户或者密码错误2");
                response.sendRedirect("login.jsp");
            }
        }else{
            session.setAttribute("msg","验证码输入错误");
            response.sendRedirect("login.jsp");
        }
    }
}
